package com.comleader.baseproject.service;

import com.comleader.baseproject.common.bean.response.ResponseCodeEnum;
import com.comleader.baseproject.common.bean.response.ResponseResult;
import com.comleader.baseproject.common.exception.ExceptionCast;
import com.comleader.baseproject.domain.Demo;
import com.comleader.baseproject.domain.DemoExample;
import com.comleader.baseproject.mapper.DemoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DemoService {

    @Autowired
    private DemoMapper demoMapper;

    /**
     *根据id查询登录用户
     * @param id 用户唯一id
     */
    public Demo selectById(String id) {
        // 执行查询
        Demo demo = demoMapper.selectByPrimaryKey(Integer.valueOf(id));
        if (demo == null){
            // 返回空值校验
            ExceptionCast.cast(ResponseCodeEnum.NULL_RESULT);
        }
        return demo;
    }

    /**
     * 根据名称查询
     * @param name
     * @return
     */
    public List<Demo> selectByName(String name) {
        // 封装example查询条件
        DemoExample demoExample = new DemoExample();
        DemoExample.Criteria criteria = demoExample.createCriteria(); // 构建查询条件
        criteria.andNameEqualTo(name);
        // 执行模糊查询
        criteria.andNameLike("%"+name+"%");
        //指定排序规则，参数1是数据库中的列名，参数二是排序规格，ASC升序，DESC降序，多个条件用逗号分隔
        demoExample.setOrderByClause("name ASC,age DESC");
        // 执行查询
        List<Demo> demos = demoMapper.selectByExample(demoExample);
        if (demos == null || demos.size() == 0){
            // 返回空值校验
            ExceptionCast.cast(ResponseCodeEnum.NULL_RESULT);
        }
        return demos;
    }

    public ResponseResult add(Demo demo) {
        demoMapper.insertSelective(demo); // 允许空值的插入
        demoMapper.insert(demo); // 不允许空值的插入
        return ResponseResult.SUCCESS();
    }

    public ResponseResult update(Demo demo) {
        demoMapper.updateByPrimaryKey(demo);
        return ResponseResult.SUCCESS();
    }
}
